<?php
/**
 * Copyrigh () 2017 湖南魔工坊科技有限公司 版权所有
 * 网址：http://www.mogo.club
 * 项目名称：环球世界交易平台
 * 文件名称：Finance.php
 * 时间：2017年8月25日
 * 作者：
 */

namespace app\world\model;

use think\Model;
use traits\model\SoftDelete;
use think\Db;

class Order extends Model
{
    /**
     * 设置软删除
     * @author
     */
    use SoftDelete;
    /**
     * 设置数据库表名
     * @author
     */
    protected $table = 'dp_world_order';
    /**
     * 自动写入时间戳
     * @author
     */
    protected $autoWriteTimestamp = true;

    /**
     * 关联資產表
     * @author
     */
    public function goods()
    {
        return $this->belongsTo('Goods');
    }

    /**
     * 关联用户表-普通用户
     * @author
     */
    public function user()
    {
        return $this->belongsTo('User');
    }

    /**
     * 关联用户表-股东用户
     * @author
     */
    public function userP()
    {
        return $this->belongsTo('User', 'pid');
    }

    /**
     * 关联订单表-上级订单
     * @author
     */
    public function order()
    {
        return $this->belongsTo('Order');
    }


    /**
     * 新增订单
     * @param $data  订单信息
     * @return $this
     */
    public function add_order($data)
    {
        return self::create($data);
    }


    /**
     * 修改订单
     * @param $data  修改信息
     * @return $this
     */
    public function edit_order($data)
    {
        return self::update($data);
    }


    /**
     * 查询所有数据并分页
     * @param string $map 查询条件
     * @param string $order 排序
     * @param string $p 每页条数
     * @param $is_page  是否分页查询
     * @return \think\Paginator
     */
    public function get_select($map = '', $order = '', $p = '', $is_page = true)
    {

        if ($is_page) {
            return self::where($map)->order($order)->paginate($p);
        }
        return self::where($map)->select();
    }


    /**
     * 视图查询订单并分页
     * @param string $map 查询条件
     * @param string $order 排序方式
     * @param string $p 分页页数
     * @return \think\Paginator 1为不分页，0为分页
     */
    public function get_list($map = '', $order = '', $p = '', $type = 0)
    {
        if ($type) {
            return self::view('world_order', true)
                ->view('world_goods', ['name' => 'goods_name', 'money' => 'goods_money'], 'world_goods.id=world_order.goods_id')
                ->where($map)
                ->order($order)
                ->select();
        } else {
            return self::view('world_order', true)
                ->view('world_goods', ['name' => 'goods_name', 'money' => 'goods_money'], 'world_goods.id=world_order.goods_id')
                ->where($map)
                ->order($order)
                ->paginate($p);
        }
    }


    /**
     * 查询一个订单
     * @param string $map 查询条件
     * @return array|false|\PDOStatement|string|Model
     */
    public function get_find($map = '')
    {
        return self::view('world_order', true)
            ->view('world_goods', ['name' => 'goods_name', 'money' => 'goods_money'], 'world_goods.id=world_order.goods_id')
            ->where($map)
            ->find();
    }


    /**
     * join用户分页输出数据
     * @param $user_id  登陆的用户id
     * @param int $type 1转出输出，2转入数据
     * @param int $p 分页数
     * @return \think\Paginator
     */
    public function get_record($user_id, $type, $order = '', $p = 15)
    {
        if ($type == 1) { //转出
            $data = Db::table('dp_world_order')
                ->join('dp_world_user', 'dp_world_order.user_id=dp_world_user.id')
                ->join('dp_world_goods', 'dp_world_order.goods_id=dp_world_goods.id')
                ->field('dp_world_user.username,dp_world_user.nickname,dp_world_goods.name,dp_world_order.*')
                ->where(['dp_world_order.transfer_id' => $user_id, 'dp_world_order.is_transfer' => 1])
                ->order($order)
                ->paginate($p);

        } else if ($type == 2) { //收入
            $data = Db::table('dp_world_order')
                ->join('dp_world_user', 'dp_world_order.transfer_id=dp_world_user.id')
                ->join('dp_world_goods', 'dp_world_order.goods_id=dp_world_goods.id')
                ->field('dp_world_user.username,dp_world_user.nickname,dp_world_goods.name,dp_world_order.*')
                ->where(['dp_world_order.user_id' => $user_id, 'dp_world_order.is_transfer' => 1])
                ->order($order)
                ->paginate($p);
        }
        return @$data;
    }


    public function get_find_relation($map)
    {
        $list = self::with(['goods', 'user', 'userP', 'order'])->where($map)->find();
        return $list;
    }


    /**
     * 查询一个商品的全部买卖信息
     */
    public function get_goods_order_list($map, $order, $p = 15)
    {
        return Db::table('dp_world_order')
            ->join('dp_world_user', 'dp_world_order.user_id=dp_world_user.id')
            ->join('dp_world_goods', 'dp_world_order.goods_id=dp_world_goods.id')
            ->field('dp_world_user.username,dp_world_user.nickname,dp_world_goods.name,dp_world_order.*')
            ->where($map)
            ->order($order)
            ->paginate($p);
    }


    /**
     * 查询一个商品的全部互转记录
     */
    public function get_goods_ransformation($map, $order, $p = 15)
    {
        return Db::table('dp_world_order')
            ->join('dp_world_user', 'dp_world_order.user_id=dp_world_user.id')
            ->join('dp_world_user transfer', 'dp_world_order.transfer_id=transfer.id')
            ->join('dp_world_goods', 'dp_world_order.goods_id=dp_world_goods.id')
            ->field('dp_world_user.username,dp_world_user.nickname,dp_world_goods.name,dp_world_order.*,transfer.username as p_username,transfer.nickname as p_nickname')
            ->where($map)
            ->order($order)
            ->paginate($p);
    }

    /**
     * 查询记录
     */
    public function get_subordinate_record($map, $order = '', $p = 15)
    {
        return Db::table('dp_world_order')
            ->join('dp_world_user user', 'dp_world_order.user_id=user.id')//接收人
            ->join('dp_world_user transfer', 'dp_world_order.transfer_id=transfer.id')//转出人
            ->join('dp_world_goods', 'dp_world_order.goods_id=dp_world_goods.id')
            ->field('user.username,user.nickname,dp_world_goods.name,dp_world_order.*,transfer.username as p_username,transfer.nickname as p_nickname')
            ->where($map)
            ->order($order)
            ->paginate($p);
    }

    /**
     * 查询记录
     */
    public function get_subordinate_list($map = '', $order = '', $p = '')
    {
        return self::view('world_order', true)
            ->view('world_goods', ['name' => 'goods_name', 'money' => 'goods_money'], 'world_goods.id=world_order.goods_id')
            ->view('world_user', ['username', 'nickname'], 'world_user.id=world_order.user_id')
            ->where($map)
            ->order($order)
            ->paginate($p);
    }


    /**
     * 计算配资日期
     */
    public function get_capital($id)
    {
        $data = self::get($id);
        $info = array();
        if ($data->time) {
            if ($data->end_time) {
                $info['past_time'] = floor(($data->end_time - $data->time) / 86400) + 1;
                $info['redeem_money'] = ($info['past_time']) * $data->capital_interest * $data->selling_money;
                $info['redeem_money'] = $this->sctonum($info['redeem_money']);
            } else {
                $info['past_time'] = floor((time() - $data->time) / 86400) + 1;
                $info['redeem_money'] = ($info['past_time']) * $data->capital_interest * $data->selling_money;
                $info['redeem_money'] = $this->sctonum($info['redeem_money']);
            }
        } else {
            $info['past_time'] = 0;
            $info['redeem_money'] = 0;
        }
        return $info;
    }

    /**
     * 把科学记数法转换成数字
     * @param $num
     * @param int $double
     * @return string
     */
    function sctonum($num, $double = 5)
    {
        if (false !== stripos($num, "e")) {
            $a = explode("e", strtolower($num));
            return bcmul($a[0], bcpow(10, $a[1], $double), $double);
        }
        return $num;
    }
    /**
     * 全资购买做空 自动平仓  买亏
     */
    public function automatic_warehouse(){

        $map=array(
            'world_order.buy_type'=>2,
            'world_order.type'=>1,
            'world_order.status'=>['in',[1,3]],
            'world_order.surplus_sum'=>['>',0]
        );
        $orders=$this->get_list($map,'','',1);//查询出所有做空的订单 和产品最新的价格

        if(!empty($orders)){
            foreach ($orders as $key => $val){
                    if($val['money']*2-$val['goods_money']<=0){//已经亏损完 进行平仓
                        //1.新增卖出记录  //2.不用扣钱 用户跟股东都不需要
                        //3.发通知给用户
                        $NewsUser = new NewsUser();
                        $con = new Configs();
                        $con_data = $con->get_find('purchase_fee,sell_fee');
                        $data['sell_fee'] = $con_data->sell_fee;
                        $data['order_id'] = $val['id'];
                        $data['type'] = 2;
                        $data['pid'] = $val['pid'];
                        $data['user_id'] = $val['user_id'];
                        $data['goods_id'] = $val['goods_id'];
                        $data['money'] = $val['money'];
                        $data['money2'] = $val['goods_money'];
                        $data['sum'] = $val['sum'];
                        $data['buy_type']=$val['buy_type'];
                        $data['actual_sum'] = $val['sum'];
                        $data['surplus_sum'] = $val['sum'];
                        $data['status']=1;
                        $data['surplus_sum']=1;
                        $data['sell_type']=2;//自动平仓
                        $this->add_order($data);//增加卖出记录
                        //减去买入记录中的购买数量
                        self::update(['surplus_sum'=>0],['id'=>$val['id']]);

                        $NewsUser->title = '資產消息。Asset message';
                        $NewsUser->user_id = $val['user_id'];
                        $NewsUser->content = '您的資產已經虧損完，系統已經為您自動平倉。Your assets have been lost and the system has been automatically closed for you  ';
                        $NewsUser->save();

                    }
            }

        }


    }

}